package com.itboye.sunsun_china.www.aq;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.itboye.sunsun_china.util.GetModelInfo;
import com.itboye.sunsun_china.util.HttpRequest;
import com.itboye.sunsun_china.volley.MyJsonRequest;
import com.itboye.sunsun_china.volley.XErrorListener;
import com.itboye.sunsun_china.volley.XRequestListener;
import com.itboye.sunsun_china.www.aq.base.AqDateTime;
import com.itboye.sunsun_china.www.aq.base.AqDevice;
import com.itboye.sunsun_china.www.aq.base.AqDeviceInfo;
import com.itboye.sunsun_china.www.aq.base.AqDeviceMessage;
import com.itboye.sunsun_china.www.aq.base.AqDeviceMessage.AqDeviceMessageType;
import com.itboye.sunsun_china.www.aq.base.MessageWhat;
import com.itboye.sunsun_china.www.aq.base.MyApplication;

/**
 * 日期：2015-04-30 1. 添加版本识别功能，支持AQ107、AQ209和AQ805设备 日期：2015-05-05 1. 添加手动添加设备功能
 */
@SuppressLint("NewApi")
public class DeviceActivity extends ActionBarActivity {

	MyApplication mApp;
	boolean mReadyExit;
	ListView mListView;
	Context mContext;
	AqDeviceInfo mSelectDeviceInfo;
	private ProgressDialog mProgressDialog;
	private JSONObject out;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_device);
		mApp = (MyApplication) getApplication();
		// mApp.init();
		mContext = this;
		mApp.mDeviceUi = this;
		mReadyExit = false;
		mSelectDeviceInfo = null;
		mListView = (ListView) findViewById(R.id.device_listView);
		// 列表项短按键处理
		mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				mSelectDeviceInfo = mApp.mMyDeviceList.get(position);
				mProgressDialog = ProgressDialog.show(DeviceActivity.this,
						mSelectDeviceInfo.mDeviceName, "连接中，请稍后……");
				// 连接线程
				new Thread(new Runnable() {
					@Override
					public void run() {
						mApp.mCurrentDevice = new AqDevice(mApp.mHandler,
								mApp.mDatabase, mApp.mPush.getClientID(),
								mSelectDeviceInfo);
						mApp.mCurrentDevice.asyncConnect();
					}
				}).start();
			}
		});

		// 列表项长按键处理
		mListView
				.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
					@Override
					public boolean onItemLongClick(AdapterView<?> parent,
							View view, int position, long id) {
						mSelectDeviceInfo = mApp.mMyDeviceList.get(position);
						mApp.mEditDeviceInfo = mSelectDeviceInfo;
						Intent mainIntent = new Intent(DeviceActivity.this,
								EditDeviceActivity.class);
						DeviceActivity.this.startActivity(mainIntent);
						return true;
					}
				});
		refreshDeviceList();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_device, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.device_action_settings1) {
			// 一键配置
			Intent mainIntent = new Intent(DeviceActivity.this,
					SmartConfigActivity.class);
			DeviceActivity.this.startActivity(mainIntent);
			return true;
		}
		if (id == R.id.device_action_settings2) {
			// 添加局域网设备
			Intent mainIntent = new Intent(DeviceActivity.this,
					AddDeviceActivity.class);
			DeviceActivity.this.startActivity(mainIntent);
			return true;
		}
		if (id == R.id.device_action_settings3) {
			// 手动添加设备
			Intent mainIntent = new Intent(DeviceActivity.this,
					ManualAddDeviceActivity.class);
			DeviceActivity.this.startActivity(mainIntent);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	// @Override
	// public boolean onKeyDown(int keyCode, KeyEvent event) {
	// // 如果是返回键
	// if (keyCode == KeyEvent.KEYCODE_BACK) {
	// if (!mReadyExit) {
	// mReadyExit = true;
	// Toast.makeText(mContext, "再按一次返回键退出", Toast.LENGTH_SHORT).show();
	// // 延时恢复
	// new Handler().postDelayed(new Runnable() {
	// public void run() {
	// mReadyExit = false;
	// }
	// }, 3000);
	// } else {
	// mReadyExit = false;
	// System.exit(0);
	// }
	// return false;
	// }
	// return super.onKeyDown(keyCode, event);
	// }

	public void refreshDeviceList() {
		ArrayList<HashMap<String, Object>> listItems = new ArrayList<HashMap<String, Object>>();
		for (int i = 0; i < mApp.mMyDeviceList.size(); i++) {
			AqDeviceInfo deviceInfo = mApp.mMyDeviceList.get(i);
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("ItemName", deviceInfo.mDeviceName);
			map.put("ItemDid", "DID : " + deviceInfo.mDid);
			map.put("ItemState1", "");
			map.put("ItemState2", "");
			map.put("ItemRightArrow", R.drawable.ic_right_arrow);
			listItems.add(map);
		}
		SimpleAdapter listItemsAdapter = new SimpleAdapter(this, listItems,
				R.layout.device_item, new String[] { "ItemName", "ItemDid",
						"ItemState1", "ItemState2", "ItemRightArrow" },
				new int[] { R.id.textView_dev_name, R.id.textView_dev_did,
						R.id.textView_dev_state1, R.id.textView_dev_state2,
						R.id.imageView_dev_right_arrow });
		mListView.setAdapter(listItemsAdapter);
	}

	/***
	 * "did":"SSAQ-004418-LYPTJ","type":"smartconfig","log":"获取设备信息失败","context"
	 * :
	 * "{\"mobileNetworkCode\":\"02\",\"password\":\"RSdUFSZG\",\"did\":\"SSAQ-004418-LYPTJ\",\"appVersion\":\"2.4.4\",\"wifiName\":\"博也内部员工使用\",\"version\":\"iPhone8,1\",\"type\":\"iOS\",\"currentRadioAccessTechnology\":\"CTRadioAccessTechnologyLTE\",\"wifi\":\"30:fc:68:c9:b4:f1\"}"
	 * 
	 * @param mMessageType
	 */
	private void connectFailedProcess(AqDeviceMessageType mMessageType) {
		try {
			out = new JSONObject();

			JSONObject info = new JSONObject();
			out.put("did", mSelectDeviceInfo.mDid);
			out.put("type", "DEVICE_LINKING");
			out.put("context", info);
			out.put("log", "连接超时");
			info.put("mobileNetworkCode",
					GetModelInfo.GetNetworkType());
			info.put("password", mApp.mWifiPassword);
			info.put("did", mSelectDeviceInfo.mDid);
			info.put("appVersion", GetModelInfo
					.getAppVersionName(MyApplication.context));
			info.put("wifiName", "wifiname");
			info.put("version", GetModelInfo
					.getAppVersionName(MyApplication.context));

			info.put("type", "DEVICE_LINKING");
			info.put("currentRadioAccessTechnology", "");
			info.put("wifi", mApp.mWifiSSID);
			out.put("context", info);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		MyJsonRequest<Object> request = new MyJsonRequest.Builder<Object>()
				.apiVer("100")
				.typeKey("BY_Log_deviceLog")
				.param("did", mSelectDeviceInfo.mDid)
				.param("context",
						out.toString())
				.param("log", mMessageType + "\t获取设备信息失败")
				.param("type", "DEVICE_LINKING")
				.requestListener(new XRequestListener<Object>() {

					@Override
					public void onResponse(Object arg0) {

					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
					}
				}).build();
		HttpRequest.getDefaultRequestQueue().add(request);
		try {
			if (mApp.mCurrentDevice != null) {
				if (mApp.mCurrentDevice.mInitState == false) {
					mProgressDialog.dismiss();
					Toast.makeText(mContext, "连接设备失败", Toast.LENGTH_SHORT)
							.show();
					if (mApp.mCurrentDevice != null) {
						mApp.mCurrentDevice.closeConnect();
					}
				}
			}
		} catch (Exception e) {
		}
	}

	public void newMessage(Message msg) {
		if (msg.what == MessageWhat.DeviceMessage) {
			AqDeviceMessage msgObj = (AqDeviceMessage) msg.obj;
			switch (msgObj.mMessageType) {
			case GetVersionOk:
				try {
					if (mApp.mCurrentDevice != null) {
						if (mApp.mCurrentDevice.mInitState == false) {
							switch (mApp.mCurrentDevice.mDeviceInfo.mDeviceType) {
							case AQ107:
							case AQ209:
							case AQ208:
							case AQ211:
								// mApp.mCurrentDevice.linuxReboot();// 重启设备
								mProgressDialog.setMessage("版本获取成功，正在读取状态……");
								mApp.mCurrentDevice.getState();
								break;
							case AQ805:
								// mApp.mCurrentDevice.linuxReboot();// 重启设备
								mProgressDialog.setMessage("版本获取成功，正在获取订阅令牌……");
								mApp.mCurrentDevice.getSubscribeToken(true,
										true, true);
								break;
							default:
								connectFailedProcess(msgObj.mMessageType);
								break;
							}
						}
					}
				} catch (Exception e) {
				}
				break;
			case GetVersionFailed:
				connectFailedProcess(msgObj.mMessageType);
				break;
			case GetStateOk:
				try {
					if (mApp.mCurrentDevice != null) {
						if (mApp.mCurrentDevice.mInitState == false) {
							mProgressDialog.setMessage("读取状态成功，正在同步日期时间……");
							mApp.mCurrentDevice.setDateTime(new AqDateTime());
						}
					}
				} catch (Exception e) {
				}
				break;
			case SetDatetimeOk:
				try {
					if (mApp.mCurrentDevice != null) {
						if (mApp.mCurrentDevice.mInitState == false) {
							mApp.mCurrentDevice.mInitState = true;
							// 初始化完成，进入设备控制界面
							mProgressDialog.dismiss();
							Intent mainIntent = new Intent(DeviceActivity.this,
									DeviceConsoleActivity.class);
							DeviceActivity.this.startActivity(mainIntent);
						}
					}
				} catch (Exception e) {
				}
				break;
			case SetDatetimeFailed:
				connectFailedProcess(msgObj.mMessageType);
				break;
			case GetSubscribeTokenFailed:
				connectFailedProcess(msgObj.mMessageType);
				break;
			case GetSubscribeTokenOk:
				try {
					if (mApp.mCurrentDevice != null) {
						if (mApp.mCurrentDevice.mInitState == false) {
							mProgressDialog.setMessage("读取订阅令牌成功，正在读取状态……");
							mApp.mCurrentDevice.getState();
						}
					}
				} catch (Exception e) {
				}
				break;
			case GetStateFailed:
				connectFailedProcess(msgObj.mMessageType);
				break;
			case ConnectOk:
				try {
					if (mApp.mCurrentDevice != null) {
						if (mApp.mCurrentDevice.mInitState == false) {
							mProgressDialog.setMessage("连接成功，获取设备版本……");
							mApp.mCurrentDevice.getDeviceVersion();
						}
					}
				} catch (Exception e) {
				}
				break;
			case ConnectFailed:
				connectFailedProcess(msgObj.mMessageType);
				break;
			default:
				break;
			}
		}
	}

}
